﻿package com.skcc.cop.mrtaxi4driver.biz;

import java.io.IOException;
import java.net.MalformedURLException;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.skcc.cop.mrtaxi4driver.R;
import com.skp.Tmap.TMapData;
import com.skp.Tmap.TMapMarkerItem;
import com.skp.Tmap.TMapPoint;
import com.skp.Tmap.TMapPolyLine;
import com.skp.Tmap.TMapView;



public class DriverMapActivity extends com.skcc.cop.mrtaxi4driver.BaseActivity {
	private static final String TAG = "DriverMap";
	public int back;
	private FrameLayout mapLayout;
	private TMapView mMapView = null;
	private LocationManager locationManager;
	private String provider;
	private boolean getMyLocation;
	double curLatitude, curLongitude;
	//	private Handler mChildHandler;
	public Location location = null;
	//private TMapMarkerItem tItem = new TMapMarkerItem();
	//private TMapMarkerItem tItem1 = new TMapMarkerItem();
	TMapPolyLine polyline;	
	//private String myLocX, myLocY, latitude, longitude = "";
	private Double myLocX, myLocY, latitude, longitude = 0.0;
	TMapData tmapdata;

	Criteria criteria;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_driver_map);	

		setBundle();
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		this.mapLayout = (FrameLayout)findViewById(R.id.framelayout_map);
		mMapView = new TMapView(this);
		mMapView.setSKPMapApiKey("c7c9ee81-1a9c-3c7e-9899-3b9c19a0dac2");
		mMapView.setLanguage(mMapView.LANGUAGE_KOREAN);
		mMapView.setIconVisibility(true);
		mMapView.setZoomLevel(15);
		mMapView.setMapType(mMapView.MAPTYPE_STANDARD);
		mMapView.setCompassMode(false);
		mMapView.setTrackingMode(false);

		mapLayout.addView(mMapView);




		getMyLocation = false;

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_COARSE);
		criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);

		provider = locationManager.getBestProvider(criteria, true);

		if(provider == null){

			AlertDialog.Builder ab = new AlertDialog.Builder(DriverMapActivity.this);
			ab.setMessage("위치 정보를 수신할 수 없습니다. 환경설정에서 GPS사용 또는 3G/Wi-Fi위치사용 기능을 ON으로 설정해주세요.");

			ab.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
					dialog.dismiss();

					back = 1;
				}
			});
			ab.setNegativeButton("취소", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					finish();
				}
			}).show(); 


		}else{

			checkGPS();

		}
	}


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		super.onResume();

		if(back == 1){

			Toast.makeText(DriverMapActivity.this, "다시 실행해 주세요", Toast.LENGTH_SHORT).show();

		}
		//drawPath();		

	}


	protected void getConnection(){
		Log.i(TAG, "getConnection()");

		mMapView.setSKPMapApiKey("c7c9ee81-1a9c-3c7e-9899-3b9c19a0dac2");
		double Latitude = curLatitude;
		double Longitude = curLongitude;

		//double Longitude = tpoint.getLongitude();

		mMapView.setCenterPoint(Longitude, Latitude);


		tmapdata = new TMapData();

		//구덕회------------------------------

		try {

			//TMapPoint tpoint = new TMapPoint(36.5708411, 126.985302);
			TMapPoint tpoint = new TMapPoint(curLatitude, curLongitude);
			TMapMarkerItem tItem = new TMapMarkerItem();
			Bitmap bm = BitmapFactory.decodeResource(this.getResources(), R.drawable.tms_default_pin);

			tItem.setTMapPoint(tpoint);
			tItem.setIcon(bm);
			tItem.setPosition(0.5f, 1.0f);
			mMapView.addMarkerItem("destination" , tItem);
			mMapView.setCenterPoint(this.longitude, this.latitude);

			//현재 위치 세팅
			Log.i(TAG, "curLatitude = " + curLatitude );
			Log.i(TAG, "curLongitude = " + curLongitude);
			if(curLatitude > 0 || curLongitude > 0) {
				try{
					mMapView.setIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.map_point_red));
					Log.i(TAG, "setLocationPoint");
					mMapView.setLocationPoint(curLatitude, curLongitude);
				}catch (Exception e) {e.printStackTrace();}
			}

			Log.i(TAG, "EndPoint curLatitude = " + this.latitude );
			Log.i(TAG, "EndPoint curLongitude = " + this.longitude);

			TMapPoint startpoint = new TMapPoint(curLatitude, curLongitude);
			TMapPoint endpoint = new TMapPoint(this.latitude, this.longitude);

			polyline = tmapdata.findPathData(startpoint, endpoint);

			
			mMapView.addTMapPath(polyline);
			
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FactoryConfigurationError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}




	private void checkGPS() {
		// TODO Auto-generated method stub

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_COARSE);
		criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		provider = locationManager.getBestProvider(criteria, true);

		System.out.println("provider : " + provider);

		//Toast.makeText(MainActivity.this, provider, Toast.LENGTH_SHORT).show();


		//locationManager.requestLocationUpdates(provider, 0, 30, locationListener);


		Toast.makeText(DriverMapActivity.this, "GPS 위치 정보를 얻어오는 중 입니다.", Toast.LENGTH_SHORT).show();



		Handler mHandler = new Handler();
		mHandler.postDelayed(new Runnable()
		{
			public void run() 
			{
				if(!getMyLocation)
				{
					//"GPS가 수신되지 않습니다. 위치 제공자를 네트워크로 변경합니다."
					Toast.makeText(DriverMapActivity.this, "GPS가 수신되지 않습니다. 위치 제공자를 네트워크로 변경합니다.", Toast.LENGTH_SHORT).show();

					//위치 제공자가 네트워크일 경우 현재 위치와의 정확도가 낮습니다."
					Toast.makeText(DriverMapActivity.this, "위치 제공자가 네트워크일 경우 현재 위치와의 정확도가 낮습니다.", Toast.LENGTH_SHORT).show();

					Handler mHandler = new Handler();
					mHandler.postDelayed(new Runnable(){
						public void run() {
							if(!getMyLocation){
								if(provider != null && provider.trim().length() > 0){
									locationManager.removeUpdates(locationListener);
									locationManager.requestLocationUpdates(provider, 0, 30, locationListener);

									Handler mHandler = new Handler();
									mHandler.postDelayed(new Runnable()
									{
										public void run() 
										{
											if(!getMyLocation)
											{
												location = locationManager.getLastKnownLocation(provider);
												//Location location = locationManager.isProviderEnabled((provider);
												if(location != null){
													getMyLocation = true;


													curLatitude 	= location.getLatitude();
													curLongitude 	= location.getLongitude();

													//String ku1 = Double.toString(curLatitude);
													//String ku2 = Double.toString(curLongitude);
													
													//Toast.makeText(DriverMapActivity.this, ku1 + "\n" + ku2, Toast.LENGTH_SHORT).show();

													getConnection();


												} else {
													AlertDialog.Builder builder = new AlertDialog.Builder(DriverMapActivity.this);

													builder.setTitle("위치서비스 동의하시겠습니까?");
													builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {

														@Override
														public void onClick(DialogInterface dialog, int which) {
															// TODO Auto-generated method stub
															startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);

														}
													}).setOnCancelListener(new DialogInterface.OnCancelListener() {
														@Override
														public void onCancel(DialogInterface dialog) {
															finish();
														}
													});
													builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {

														@Override
														public void onClick(DialogInterface arg0, int arg1) {
															// TODO Auto-generated method stub
															finish();
															Toast.makeText(DriverMapActivity.this, "위치설정에 동의하셔야 합니다.", Toast.LENGTH_SHORT).show();
														}
													});
													builder.show();
												}
											}
										}
									}, 1000);
								}else{
									AlertDialog.Builder builder = new AlertDialog.Builder(DriverMapActivity.this);

									builder.setTitle("위치서비스 동의하시겠습니까?");
									builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);

										}
									}).setOnCancelListener(new DialogInterface.OnCancelListener() {
										@Override
										public void onCancel(DialogInterface dialog) {
											finish();
										}
									});
									builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface arg0, int arg1) {
											// TODO Auto-generated method stub
											finish();
											Toast.makeText(DriverMapActivity.this, "위치설정에 동의하셔야 합니다.", Toast.LENGTH_SHORT).show();
										}
									});
									builder.show();
								}
							}
						}
					}, 1000);
				}
			}
		}, 1000);


	}


	LocationListener locationListener = new LocationListener() {

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub


		}
	};

	public void drawPath(){
		TMapPoint startpoint = new TMapPoint(curLatitude, curLongitude);
		TMapPoint endpoint = new TMapPoint(this.latitude, this.longitude);
		try{
			polyline = tmapdata.findPathData(startpoint, endpoint);
			//handler.sendEmptyMessage(0);
		}catch(Exception e) {e.printStackTrace();}

	}

	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch(msg.what){
			case 0:
				mMapView.addTMapPath(polyline);
				//LoadingDialog.hideLoading();
				break;
			default :
				break;

			}
			super.handleMessage(msg);
		}

	};
	
	private void setBundle() {
		Bundle bundle = getIntent().getExtras();
		this.latitude = bundle.getDouble("latitude");
		this.longitude = bundle.getDouble("longitude");
		//this.title = bundle.getString("title");
		
		//this.myLocX = bundle.getString("myLocX");
		//this.myLocY = bundle.getString("myLocY");
		//this.isPath = bundle.getBoolean("isPath");
	}


}